package com.minelx.woods.task.core;

import com.minelx.landisk.filesystem.core.File;
import com.minelx.statementsplus.CombinedSql;
import com.minelx.woods.task.common.Node;
import com.minelx.woods.task.common.NodeBuilder;

import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.IntStream;

import static com.minelx.landisk.filesystem.core.init.OpenPolicy.createANewOne;

public class MoreCombinedSqlTask implements ICombinedSqlTask {

	private final List<CombinedSql> combinedSqlList;

	private final File destinationFile;

	private final Map<String, Predicate<String>> filterers;

	public MoreCombinedSqlTask(List<CombinedSql> combinedSqlList, File destinationFile, Map<String, Predicate<String>> filterers) {
		this.destinationFile = destinationFile;
		this.combinedSqlList = combinedSqlList;
		this.filterers = filterers;
	}

	@Override
	public Node<SqlTaskValues> split(Predicate<SqlTaskValues> neededSplitting) {
		NodeBuilder<SqlTaskValues> builder = new NodeBuilder<>(new SqlTaskValues(null, destinationFile, filterers));

		// split each commitment
		IntStream.range(0, combinedSqlList.size())
				.mapToObj(index -> new SqlTaskValues(
						combinedSqlList.get(index), File.create(destinationFile.path().sibling(destinationFile.path().getName() + index + "_"), createANewOne()), filterers))
				.map(sqlTaskInfo -> sqlTaskInfo.split(neededSplitting))
				.forEach(builder::leaf);

		return builder.build();
	}
}
